package com.example.dj;

import java.util.List;

import android.support.v7.app.ActionBarActivity;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.ImageView;
import android.widget.SeekBar;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.SeekBar.OnSeekBarChangeListener;

public class PlayActivity extends ActionBarActivity {
	
	private TextView musicTitle = null;  
    private TextView musicArtist = null;  
    private ImageView previousBtn; // 上一首
    private ImageView repeatBtn;   // 重复
    private ImageView playBtn;     // 播放、播放、暂停 
    private ImageView shuffleBtn; // 随机播放  
    private ImageView nextBtn;     // 下一首
    private SeekBar music_progressBar;  //歌曲进度  
    private TextView currentProgress;   //当前进度消耗的时间
    private TextView finalProgress;     //歌曲时间 

    private String title;       //歌曲标题  
    private String artist;      //歌曲艺术家
    private String url;         //歌曲路径  
    private int listPosition;   //播放歌曲在mp3Infos的位置
    private int currentTime;    //当前歌曲播放时间  
    private int duration;       //歌曲长度  
    private int flag;           //播放标识 
    
    private int repeatState;  
    private final int isAllRepeat = 1;      // 全部循环  
    private final int isNoneRepeat = 2;     // 无重复播
    private boolean isPlaying;              // 正在播放  
    private boolean isPause;                // 暂停  
    private boolean isNoneShuffle;           // 顺序播放  
    private boolean isShuffle;          // 随机播放 
    
    private List<Mp3Info> mp3Infos;  
    
    
    private PlayerReceiver playerReceiver;    
    public static final String UPDATE_ACTION = "com.example.action.UPDATE_ACTION";  //更新动作  
    public static final String CTL_ACTION = "com.example.action.CTL_ACTION";        //控制动作  
    public static final String MUSIC_CURRENT = "com.example.action.MUSIC_CURRENT";  //音乐当前时间改变动作  
    public static final String MUSIC_DURATION = "com.example.action.MUSIC_DURATION";//音乐播放长度改变动作  
    public static final String MUSIC_PLAYING = "com.example.action.MUSIC_PLAYING";  //音乐正在播放动作  
    public static final String REPEAT_ACTION = "com.example.action.REPEAT_ACTION";  //音乐重复播放动作  
    public static final String SHUFFLE_ACTION = "com.example.action.SHUFFLE_ACTION";//音乐随机播放动作  
    
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_other);
		musicTitle = (TextView) findViewById(R.id.title);  
        musicArtist = (TextView) findViewById(R.id.artist);  
          
        findViewById();  
        setViewOnclickListener();  
        mp3Infos = MediaUtil.getMp3Infos(PlayActivity.this); 
    	playerReceiver = new PlayerReceiver();  
    	IntentFilter filter = new IntentFilter();  
        filter.addAction(UPDATE_ACTION);  
        filter.addAction(MUSIC_CURRENT);  
        filter.addAction(MUSIC_DURATION);  
       	registerReceiver(playerReceiver, filter);  
	}

	
	/** 
     * 从界面上根据id获取按钮 
     */  
    private void findViewById() {  
        repeatBtn = (ImageView) findViewById(R.id.repeat);  
        shuffleBtn = (ImageView) findViewById(R.id.shuffle);  
        previousBtn = (ImageView) findViewById(R.id.previous);  
        playBtn = (ImageView) findViewById(R.id.play);  
        nextBtn = (ImageView) findViewById(R.id.next);  
        musicTitle = (TextView) findViewById(R.id.title);  
        currentProgress = (TextView) findViewById(R.id.current_progress);
		finalProgress = (TextView) findViewById(R.id.final_progress);
    } 
    //给每个按钮设置监听
    private void setViewOnclickListener() {
		// TODO Auto-generated method stub
    	ViewOnclickListener ViewOnClickListener = new ViewOnclickListener();
		previousBtn.setOnClickListener(ViewOnClickListener);
		repeatBtn.setOnClickListener(ViewOnClickListener);
		playBtn.setOnClickListener(ViewOnClickListener);
		shuffleBtn.setOnClickListener(ViewOnClickListener);
		nextBtn.setOnClickListener(ViewOnClickListener);
		music_progressBar
				.setOnSeekBarChangeListener(new SeekBarChangeListener());
	}
    
    @Override
	protected void onStart() {
		super.onStart();
	}
    
	@Override
	protected void onPause() {
		super.onPause();
	}

	@Override  
      protected void onResume() {  
  		super.onResume();
  		Intent intent = getIntent();  
        Bundle bundle = intent.getExtras();  
        title = bundle.getString("title");  
        artist = bundle.getString("artist");  
        url = bundle.getString("url");  
        listPosition = bundle.getInt("listPosition");  
        repeatState = bundle.getInt("repeatState");  
        flag = bundle.getInt("MSG");  
        isShuffle = bundle.getBoolean("shuffleState");  
        currentTime = bundle.getInt("currentTime");  
        duration = bundle.getInt("duration");  
        initView();
      }  
  	
	private void initView() {
		// TODO Auto-generated method stub
		 musicTitle.setText(title);  
	        musicArtist.setText(artist);  
	        music_progressBar.setProgress(currentTime);  
	        music_progressBar.setMax(duration);  
	        switch (repeatState) {  
	        case isAllRepeat: // 全部循环  
	            shuffleBtn.setClickable(false);  
	            break;  
	        case isNoneRepeat: // 无重复
	            shuffleBtn.setClickable(true);  
	            break;  
	        }  
	        if(isShuffle) {  
	            isNoneShuffle = false;  
	            repeatBtn.setClickable(false);  
	        } else {  
	            isNoneShuffle = true;  
	            repeatBtn.setClickable(true);  
	        }  
	        if(flag == AppConstant.PlayerMsg.PLAYING_MSG) { //如果播放信息是正在播放
	            Toast.makeText(PlayActivity.this, "正在播放--" + title, 1).show();  
	        }  
	        else if(flag == AppConstant.PlayerMsg.PLAY_MSG) { //如果是点击列表播放歌曲的内容
	            play();  
	        }  
	        isPlaying = true;  
	        isPause = false;  
	}
	
	@Override  
	protected void onStop() {  
	    super.onStop();  
	    unregisterReceiver(playerReceiver);
	}  
	      
	@Override  
	protected void onDestroy() {  
		super.onDestroy();  
	}
	
	private class ViewOnclickListener implements OnClickListener {
		Intent intent = new Intent();
		@Override
		public void onClick(View v) {
			// TODO Auto-generated method stub
			switch (v.getId()) {  
            case R.id.play:
            	if (isPlaying) {  
                    intent.setAction("com.example.media.MUSIC_SERVICE");  
                    intent.putExtra("MSG", AppConstant.PlayerMsg.PAUSE_MSG);  
                    startService(intent);  
                    isPlaying = false;  
                    isPause = true;  
            	} else if (isPause) {  
                    intent.setAction("com.example.media.MUSIC_SERVICE");  
                    intent.putExtra("MSG", AppConstant.PlayerMsg.CONTINUE_MSG);  
                    startService(intent);  
                    isPause = false;  
                    isPlaying = true;  
                }  
                break;  
            case R.id.repeat: // 重复播放  
            	if (repeatState == isAllRepeat) {  
                    repeat_none();  
                    shuffleBtn.setClickable(true);  
                    repeatState = isNoneRepeat;  
                }  
            	Intent intent = new Intent(REPEAT_ACTION);
                switch (repeatState) {
				case isAllRepeat: // 全部循环
					Toast.makeText(PlayActivity.this, null,
							Toast.LENGTH_SHORT).show();
					intent.putExtra("repeatState", isAllRepeat);
					sendBroadcast(intent);
					break;
				case isNoneRepeat: // 无重复
					Toast.makeText(PlayActivity.this, null,
							Toast.LENGTH_SHORT).show();
					intent.putExtra("repeatState", isNoneRepeat);
					break;
				}
                break;  
            case R.id.previous:       //上一首歌
                previous();  
                break; 
            case R.id.next: // 下一首歌
            	next(); 
                break;  
            case R.id.shuffle: // 随机播放  
            	Intent shuffleIntent = new Intent(SHUFFLE_ACTION); 
            	if (isNoneShuffle) {  
                    Toast.makeText(PlayActivity.this, 
                            null, Toast.LENGTH_SHORT).show();  
                    isNoneShuffle = false;  
                    isShuffle = true;  
                    shuffleMusic();  
                    repeatBtn.setClickable(false);
                    repeatBtn.setClickable(false);  
					shuffleIntent.putExtra("shuffleState", true);  
                    sendBroadcast(shuffleIntent);
                } else if (isShuffle) {  
                    Toast.makeText(PlayActivity.this, null,  
                            Toast.LENGTH_SHORT).show();  
                    isShuffle = false;  
                    isNoneShuffle = true;  
                    repeatBtn.setClickable(true);  
                    shuffleIntent.putExtra("shuffleState", false);
					sendBroadcast(shuffleIntent);
                }  
                break;  
            }  
		}
	}

	private void next() {
		// TODO Auto-generated method stub
		listPosition = listPosition + 1;  
        if(listPosition <= mp3Infos.size() - 1) {  
            Mp3Info mp3Info = mp3Infos.get(listPosition);  //下一首
            musicTitle.setText(mp3Info.getTitle());  
            Intent intent = new Intent();  
            intent.setAction("com.example.media.MUSIC_SERVICE");  
            intent.putExtra("listPosition", listPosition);  
            intent.putExtra("url", mp3Info.getUrl());  
            intent.putExtra("MSG", AppConstant.PlayerMsg.NEXT_MSG);  
            startService(intent);  
        } else {  
            Toast.makeText(PlayActivity.this, "没有下一首了", Toast.LENGTH_SHORT).show();  
        }  
	}
	private void previous() {
		// TODO Auto-generated method stub
		 listPosition = listPosition - 1;  
	        if(listPosition >= 0) {  
	            Mp3Info mp3Info = mp3Infos.get(listPosition);   //上一首
	            musicTitle.setText(mp3Info.getTitle());  
	            musicArtist.setText(mp3Info.getArtist());  
	            url = mp3Info.getUrl();  
	            Intent intent = new Intent();  
	            intent.setAction("com.example.media.MUSIC_SERVICE");  
	            intent.putExtra("url", mp3Info.getUrl());  
	            intent.putExtra("listPosition", listPosition);  
	            intent.putExtra("MSG", 
	            		AppConstant.PlayerMsg.PRIVIOUS_MSG);  
	            startService(intent);  
	        }  
	        else {  
	            Toast.makeText(PlayActivity.this, "没有上一首了", Toast.LENGTH_SHORT).show();  
	        }  
	}
	
	private void play() {
		// 默认播放的时候为顺序播放
		repeat_none();
		Intent intent = new Intent();
		intent.setAction("com.example.media.MUSIC_SERVICE");
		intent.putExtra("url", url);
		intent.putExtra("listPosition", listPosition);
		intent.putExtra("MSG", flag);
		startService(intent);
	}
    //全部循环 
    public void repeat_all() {  
        Intent intent = new Intent(CTL_ACTION);  
        intent.putExtra("control", 1);  
        sendBroadcast(intent);  
    }  
  
    //顺序播放 
    public void repeat_none() {  
        Intent intent = new Intent(CTL_ACTION);  
        intent.putExtra("control", 2);  
        sendBroadcast(intent);  
    }  
      
    //随机播放 
    public void shuffleMusic() {  
        Intent intent = new Intent(CTL_ACTION);  
        intent.putExtra("control", 3);  
        sendBroadcast(intent);  
    }  

	
	private class SeekBarChangeListener implements OnSeekBarChangeListener {

		@Override
		public void onProgressChanged(SeekBar seekBar, int progress,
				boolean fromUser) {
				if (fromUser) {
					audioTrackChange(progress); // 用户控制进度的改动
				}
			}
			private void audioTrackChange(int progress) {
			// TODO Auto-generated method stub
				Intent intent = new Intent();
				intent.setAction("com.example.media.MUSIC_SERVICE");
				intent.putExtra("url", url);
				intent.putExtra("listPosition", listPosition);
				intent.putExtra("MSG", AppConstant.PlayerMsg.PROGRESS_CHANGE);
				intent.putExtra("progress", progress);
				startService(intent);
		}
			@Override
			public void onStartTrackingTouch(SeekBar seekBar) {
				// TODO Auto-generated method stub
				
			}

			@Override
			public void onStopTrackingTouch(SeekBar seekBar) {
				// TODO Auto-generated method stub
				
			}
		}
	public class PlayerReceiver extends BroadcastReceiver{
		 @Override  
	        public void onReceive(Context context, Intent intent) {  
	            String action = intent.getAction();  
	            if(action.equals(MUSIC_CURRENT)) {  
	                currentTime = intent.getIntExtra("currentTime", -1);  
	                currentProgress.setText(MediaUtil.formatTime(currentTime));  
	                music_progressBar.setProgress(currentTime);  
	            } else if(action.equals(MUSIC_DURATION)) {  
	                int duration = intent.getIntExtra("duration", -1);  
	                music_progressBar.setMax(duration);  
	                finalProgress.setText(MediaUtil.formatTime(duration));  
	            } else if(action.equals(UPDATE_ACTION)) {  
	                //获取Intent中的current消息，current代表当前正在播放的歌曲
	                listPosition = intent.getIntExtra("current", -1);  
	                url = mp3Infos.get(listPosition).getUrl();  
	                if(listPosition >= 0) {  
	                    musicTitle.setText(mp3Infos.get(listPosition).getTitle());  
	                    musicArtist.setText(mp3Infos.get(listPosition).getArtist());  
	                }  
	                if(listPosition == 0) {  
	                    finalProgress.setText(MediaUtil.formatTime(mp3Infos.get(listPosition).getDuration()));  
	                    isPause = true;  
	                }  
	            }  
	        }  
	          
	    }  

}
